package com.rabbit.springrabbitmq.producer;

import com.rabbit.springrabbitmq.entity.Order;
import com.rabbit.springrabbitmq.producer.confrim.ConfirmCallBack;
import com.rabbit.springrabbitmq.producer.returns.ReturnCallBack;
import org.springframework.amqp.core.MessagePropertiesBuilder;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.UUID;

/**
 * @Author: JohnCoding
 * @Description:
 * @date: 2020/8/7 22:11
 */
@Component
public class RabbitSender {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 发送消息
     * @param message
     * @param properties
     * @throws Exception
     */
    public void send(Object message, Map<String, Object> properties) throws Exception {
        MessageHeaders headers = new MessageHeaders(properties);
        Message<Object> msg = MessageBuilder.createMessage(message, headers);
        rabbitTemplate.setConfirmCallback(new ConfirmCallBack());
        rabbitTemplate.setReturnCallback(new ReturnCallBack());
        CorrelationData correlationData = new CorrelationData();
        correlationData.setId(UUID.randomUUID().toString()); // 标志着是发送该消息的唯一属性，可以是UUID+时间戳
        rabbitTemplate.convertAndSend("exchange-1", "springboot.hello", msg,correlationData);
    }

    /**
     * 发送消息
     * @param order
     * @throws Exception
     */
    public void sendOrder(Order order) throws Exception {
        rabbitTemplate.setConfirmCallback(new ConfirmCallBack());
        rabbitTemplate.setReturnCallback(new ReturnCallBack());
        CorrelationData correlationData = new CorrelationData();
        correlationData.setId(UUID.randomUUID().toString()); // 标志着是发送该消息的唯一属性，可以是UUID+时间戳
        rabbitTemplate.convertAndSend("exchange-2", "springboot.def", order,correlationData);
    }


}
